package com.gomoku;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.List;

public class LoadReplayFrame extends JFrame {
    private GameLogic gameLogic;
    private List<int[]> moveHistory;
    private int currentMoveIndex;

    private JButton[][] boardButtons;
    private JLabel statusLabel;
    private JButton prevButton;
    private JButton nextButton;
    private JButton restartButton;
    private JButton backButton;

    public LoadReplayFrame() {
        gameLogic = new GameLogic();
        moveHistory = new ArrayList<>();
        currentMoveIndex = -1;

        setTitle("加载游戏记录");
        setSize(600, 600);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);
        setResizable(false);

        initComponents();
    }

    private void initComponents() {
        JPanel boardPanel = new JPanel(new GridLayout(GameLogic.BOARD_SIZE, GameLogic.BOARD_SIZE));
        boardButtons = new JButton[GameLogic.BOARD_SIZE][GameLogic.BOARD_SIZE];

        for (int i = 0; i < GameLogic.BOARD_SIZE; i++) {
            for (int j = 0; j < GameLogic.BOARD_SIZE; j++) {
                JButton button = new JButton();
                button.setPreferredSize(new Dimension(40, 40));
                button.setOpaque(true);
                button.setBorder(BorderFactory.createLineBorder(Color.BLACK));
                button.setBackground(new Color(220, 179, 92));

                boardButtons[i][j] = button;
                boardPanel.add(button);
            }
        }

        statusLabel = new JLabel("请选择游戏记录文件", JLabel.CENTER);
        statusLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));

        JButton loadButton = new JButton("加载游戏记录");
        loadButton.addActionListener(e -> loadGameRecord());

        prevButton = new JButton("上一步");
        prevButton.setEnabled(false);
        prevButton.addActionListener(e -> {
            if (currentMoveIndex > 0) {
                currentMoveIndex--;
                loadMove(currentMoveIndex);
                updateButtonStates();
            }
        });

        nextButton = new JButton("下一步");
        nextButton.setEnabled(false);
        nextButton.addActionListener(e -> {
            if (currentMoveIndex < moveHistory.size() - 1) {
                currentMoveIndex++;
                loadMove(currentMoveIndex);
                updateButtonStates();
            }
        });

        restartButton = new JButton("重新开始");
        restartButton.setEnabled(false);
        restartButton.addActionListener(e -> {
            currentMoveIndex = -1;
            gameLogic.resetGame();
            updateBoard();
            updateButtonStates();
            statusLabel.setText("游戏已重置");
        });

        backButton = new JButton("返回");
        backButton.addActionListener(e -> {
            dispose();
            new ReplayMenu().setVisible(true);
        });

        JPanel controlPanel = new JPanel(new GridLayout(1, 4));
        controlPanel.add(prevButton);
        controlPanel.add(nextButton);
        controlPanel.add(restartButton);
        controlPanel.add(backButton);

        add(boardPanel, BorderLayout.CENTER);
        add(statusLabel, BorderLayout.NORTH);
        add(loadButton, BorderLayout.SOUTH);
        add(controlPanel, BorderLayout.PAGE_END);
    }

    private void loadGameRecord() {
        JFileChooser fileChooser = new JFileChooser();
        int returnValue = fileChooser.showOpenDialog(this);

        if (returnValue == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
                moveHistory.clear();
                String line;
                while ((line = reader.readLine()) != null) {
                    String[] parts = line.split(",");
                    int row = Integer.parseInt(parts[0]);
                    int col = Integer.parseInt(parts[1]);
                    moveHistory.add(new int[]{row, col});
                }

                currentMoveIndex = -1;
                gameLogic.resetGame();
                updateBoard();
                updateButtonStates();
                statusLabel.setText("已加载游戏记录，共 " + moveHistory.size() + " 步");
                nextButton.setEnabled(true);

            } catch (IOException e) {
                JOptionPane.showMessageDialog(this, "读取文件失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void loadMove(int index) {
        gameLogic.resetGame();
        for (int i = 0; i <= index; i++) {
            int[] move = moveHistory.get(i);
            gameLogic.makeMove(move[0], move[1]);
        }
        updateBoard();

        String currentPlayer = gameLogic.getCurrentPlayer() == 1 ? "黑方" : "白方";
        if (index == moveHistory.size() - 1) {
            statusLabel.setText("第 " + (index + 1) + " 步 - 游戏结束 - " + currentPlayer + "获胜");
        } else {
            statusLabel.setText("第 " + (index + 1) + " 步 - " + currentPlayer + "回合");
        }
    }

    private void updateBoard() {
        int[][] board = gameLogic.getBoard();

        for (int i = 0; i < GameLogic.BOARD_SIZE; i++) {
            for (int j = 0; j < GameLogic.BOARD_SIZE; j++) {
                Color color;
                switch (board[i][j]) {
                    case 1: color = Color.BLACK; break;
                    case 2: color = Color.WHITE; break;
                    default: color = new Color(220, 179, 92); break;
                }
                boardButtons[i][j].setBackground(color);
            }
        }
    }

    private void updateButtonStates() {
        prevButton.setEnabled(currentMoveIndex > 0);
        nextButton.setEnabled(currentMoveIndex < moveHistory.size() - 1 && !moveHistory.isEmpty());
        restartButton.setEnabled(!moveHistory.isEmpty());
    }
}